package com.stlm2.controller;

import com.stlm2.dems.entity.DdmGoods;
import com.stlm2.dems.service.DdmGoodsService;
import com.stlm2.dems.service.GoodSpecificationService;
import com.stlm2.dems.entity.Specification;
import com.stlm2.dems.service.SpecificationService;
import com.stlm2.dems.entity.SpecificationContent;
import com.stlm2.dems.service.SpecificationContentService;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.entity.User;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;

/**
 * Author：fuchunyu
 * Date：2017/9/11
 * Description：
 */
@Controller
@RequestMapping("/specificationContentC")
public class SpecificationContentController {

    @Resource
    private SpecificationService specificationService;
    @Resource
    private UserDao userDao;
    @Resource
    private SpecificationContentService specificationContentService;
    @Resource
    private GoodSpecificationService goodSpecificationService;
    @Resource
    private DdmGoodsService ddmGoodsService;

    @RequestMapping(value="/listView",produces="application/json;charset=UTF-8")
    public ModelAndView listView(ModelAndView modelAndView){
        modelAndView.setViewName("/specificationContent/list");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping(value = "/addSpecificationContent.json",produces = "application/json;charset=UTF-8")
    public String addSpecificationContent(Integer specificatonid,String specificationContentName,String token){

        User user=userDao.getByToken(token);
        if(user==null)
           return CodeContent.returnLogin();

        Specification specification=specificationService.findEntityById(specificatonid);
        if(specification==null)
            CodeContent.returnFailure("获取规格失败！");
        DdmGoods goods=ddmGoodsService.findEntityById(specification.getGoodId());
        if (goods==null)
            return CodeContent.returnFailure("没有找到商品！");
        if(goods.getState())
            return CodeContent.returnFailure("请先下架商品再做修改！");
        SpecificationContent specificationContent=new SpecificationContent();
        specificationContent.setGoodId(specification.getGoodId());
        specificationContent.setContent(specificationContentName);
        specificationContent.setCreateTime(new Date());
        specificationContent.setCreateUserId(user.getId());
        specificationContent.setSpecificationId(specification.getId());
        specificationContent.setIsValid(true);

        specificationContentService.addEntity(specificationContent);

        return CodeContent.returnSuccess(null);
    }

    @ResponseBody
    @RequestMapping(value = "/getSpecificationContentAll.json",produces = "application/json;charset=UTF-8")
    public String getSpecificationContentAll(Integer goodid){
        List<SpecificationContent> list=specificationContentService.getSpecificationContentAll(goodid);
        return CodeContent.returnSuccess(specificationContentService.conventAll(list));
    }

    @ResponseBody
    @RequestMapping(value = "/detailsSpecificationContent.json",produces = "application/json;charset=UTF-8")
    public String detailsSpecificationContent(Integer id){
        SpecificationContent specificationContent  = specificationContentService.findEntityById(id);
        return CodeContent.returnSuccess(specificationContentService.builderModelAll(specificationContent));
    }

    @ResponseBody
    @RequestMapping(value="/updateSpecificationContent.json",produces = "application/json;charset=UTF-8")
    public String updateSpecificationContent(String token,Integer specificationContentId,String content,String isValid){

        User user=userDao.getByToken(token);
        Map<String,String> map=new HashMap<String, String>();
        if(user==null)
           return CodeContent.returnSuccess(null);

        SpecificationContent specificationContent=specificationContentService.findEntityById(specificationContentId);
        if(specificationContent==null)
            return CodeContent.returnFailure("获取规格内容失败！");
        map.put("oldName",specificationContent.getContent());
        if(StringUtils.isNotEmpty(content))
            specificationContent.setContent(content);
        map.put("newName",content);
        if(StringUtils.isNotEmpty(isValid))
            specificationContent.setIsValid(BooleanUtils.toBoolean(isValid));
        specificationContentService.updateEntity(specificationContent);
        map.put("goodId",specificationContent.getGoodId().toString());
        goodSpecificationService.updatePropertiesName(map);
        return CodeContent.returnSuccess(null);
    }

    @ResponseBody
    @RequestMapping(value = "/getSpecificationContent.json",produces = "application/json;charset=UTF-8")
    public String getSpecificationContent(Integer goodid){
        Map<Integer, List<SpecificationContent>> map = new HashMap<Integer, List<SpecificationContent>>();

        map =	specificationContentService.getAllValidSpecification(goodid);

        List<SpecificationContent> list= new ArrayList<SpecificationContent>();
        List<List<String>>  listAll = new ArrayList<List<String>>();
        for (Object o : map.keySet()) {
            list = map.get(o);
            List<String>  dd = new ArrayList<String>();
            for(SpecificationContent goodsSpecification:list){
                //String a=o.toString()+":"+goodsSpecification.getContent();
                String a=o.toString()+":"+goodsSpecification.getId().toString();

                dd.add(a);
            }
            listAll.add(dd);
            //list = map.get(o);
        }
        int counterIndex = listAll.size()-1;
        int total  = 1;
        for(List<String> list0: listAll){
            total = list0.size()*total;
        }
        int[] counter =new int[listAll.size()];
        for(int i=0;i<counter.length;i++){
            counter[i]=0;
        }

        List<String> list3 = new ArrayList<String>();
        for(int k=0;k<total;k++){
            List<String> list1 = new ArrayList<String>();
            for(int q = 0;q<listAll.size();q++){
                list1.add(listAll.get(q).get(counter[q]));

            }
            String list1String =  list1.toString();
            list1String = list1String.replace("[","{");
            list1String = list1String.replace("]","}");

            list3.add(list1String);

            if(counterIndex>=0)
                handle(counter,counterIndex,listAll);
        }

        JSONArray jsonArray = new JSONArray(list3.toString());
        //JSONObject json = new JSONObject(list3.toString());
        return jsonArray.toString();
    }
    public static void handle(int[] counter,int counterIndex,List<List<String>> listAll) {
        counter[counterIndex]++;
        if (counter[counterIndex] >= listAll.get(counterIndex).size()) {
            counter[counterIndex] = 0;
            counterIndex--;
            if (counterIndex >= 0) {
                handle(counter,counterIndex,listAll);
            }
            counterIndex = listAll.size() - 1;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/keyValue.json",produces = "application/json;charset=UTF-8")
    public String getKeyValue(String keyValue){
        String specificationId = keyValue.replaceAll(":.*","");
        String goodsSpecificationId  =keyValue.replaceAll(".*:","");
        String result="";
        if(!specificationId.equals("") || !goodsSpecificationId.equals("")){
            Specification specification =  specificationService.findEntityById(Integer.parseInt(specificationId));
            SpecificationContent goodsSpecification = specificationContentService.findEntityById(Integer.parseInt(goodsSpecificationId));
            String specificationContent = specification.getName();
            String goodsSpecificationName  = goodsSpecification.getContent();
            result = specificationContent+":"+goodsSpecificationName;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/addSpecificationAndContent.json",produces = "application/json;charset=UTF-8")
    public String addSpecificationAndContent(String token,String goodid,String specificationName1,String specifcationContentName1,String specificationName2,String specifcationContentName2){
        User user=userDao.getByToken(token);
        if (user==null)
            return CodeContent.returnLogin();
        if(!NumberUtils.isDigits(goodid))
            return CodeContent.returnFailure("错误的商品ID！");
        if(StringUtils.isEmpty(specificationName1))
            return CodeContent.returnFailure("规格一不能为空！");
        if(StringUtils.isEmpty(specifcationContentName1))
            return CodeContent.returnFailure("规格内容一不能为空！");
        if(specificationName1.equals(specificationName2))
            return CodeContent.returnFailure("规格一和规格二重复！");

        List<Specification> specifications= specificationService.getByGoodId(Integer.parseInt(goodid));
        if(specifications.size()>=2)
            return CodeContent.returnFailure("已添加规格！");
        specificationContentService.addSpecification(user,goodid,specificationName1,specifcationContentName1);
        if(specifications.size()==0&&StringUtils.isNotEmpty(specificationName2)&&StringUtils.isNotEmpty(specifcationContentName2)&&specifications.size()==0)
            specificationContentService.addSpecification(user,goodid,specificationName2,specifcationContentName2);
        return CodeContent.returnSuccess(null);
    }
}
